package com.iwdnb.gkgz.common.utils;

import java.util.ArrayList;
import java.util.List;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;

import com.iwdnb.bmnf.common.utils.HttpClientUtils;
import com.iwdnb.gkgz.common.model.dto.Stock;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections4.CollectionUtils;

@Slf4j
public class StockInitUtils {

    /**
     * 获取指定类型的所有股票信息（单次查询最多返回100只股票）
     *
     * @param stockType 股票类型（深圳A股：sz_a  深圳B股：sz_b）
     * @return 返回所有符合类型的股票信息
     */
    public static List<Stock> queryStockListByType(int page, String stockType) {
        String type = stockType + "_a";
        String url = "http://vip.stock.finance.sina.com.cn/quotes_service/api/json_v2.php/Market_Center.getHQNodeData?"
            + "page=" + page +
            "&num=100" +
            "&sort=symbol" +//排序的列
            "&asc=1" +//1：升序  0：降序
            "&node=" + type +
            "&symbol=" +
            "&_s_r_a=init";//以symbol升序时 默认为init 根据其他排序时均为sort
        String body = HttpClientUtils.get(url);
        ////发送请求
        //HttpHeaders headers = new HttpHeaders();
        //HttpEntity entity = new HttpEntity<>(headers);
        //
        //ResponseEntity response = restTemplate.exchange(url, HttpMethod.GET, entity, String.class);
        //String body = response.getBody().toString();
        JSONArray resultJson = JSONArray.parseArray(body);
        if (CollectionUtils.isEmpty(resultJson)) {
            return null;
        }
        List<Stock> stockList = new ArrayList<>();
        for (int i = 0; i < resultJson.size(); i++) {
            stockList.add(transferStock(resultJson.getJSONObject(i)));
        }
        return stockList;
    }

    private static Stock transferStock(JSONObject object) {
        Stock stock = new Stock();
        String code = object.getString("symbol");
        stock.setCode(code);
        stock.setMarket(code.substring(0, 2));
        stock.setType("a");
        stock.setName(object.getString("name"));
        stock.setPrice(object.getBigDecimal("trade"));
        return stock;
    }

    public static void main(String[] args) {
        queryStockListByType(1, "sh");
    }
}
